package com.sigmatrix.h5.utils.security;

import java.security.MessageDigest;

import org.apache.commons.codec.binary.Base64;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Preconditions;

/**
 * 
 *@ClassName: TransferDecrypter
 *@Description: 
 *@author MH
 *@date 2017年8月28日 下午2:36:00
 */
public class TransferDecrypter {

    /**
     * 摘要算法名
     */
    private final static String algorithmName = "SHA-256";

    private static ObjectMapper mapper = new ObjectMapper();

    /**
     * 
     * @Title: 		 decodeTransferData2Entity   
     * @Description: 将加密传输的字符串转换为期望类型的对象
     * @param queryStr
     * @param clazz
     * @return   
     * @throws
     */
    public static <T> T decodeTransferData2Entity(String queryStr, Class<T> clazz) {
        try {
            return mapper.readValue(decodeTransferData(queryStr).getMetadata(), clazz);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 
     * @Title: 		 decodeTransferData   
     * @Description: 解密传输数据  
     * @param data 传输数据
     * @return
     * @throws Exception   
     * @throws
     */
    public static TransPackageDTO decodeTransferData(String data) throws Exception {
        byte[] decodeByte = Base64.decodeBase64(data);
        String decodeStr = new String(decodeByte);
        TransPackageDTO transPackage = mapper.readValue(decodeStr, TransPackageDTO.class);
        Preconditions.checkNotNull(transPackage, "解码后对象不能为空.");
        String digestKey = KeyHelper.getSpecifiedKey(transPackage.getKeyIndex());
        byte[] bs = MessageDigest.getInstance(algorithmName).digest((transPackage.getMetadata() + digestKey).getBytes());
        //String digest = Base64.encodeBase64URLSafeString()
        if (transPackage.getDigest().equals(new String(bs))) {
            return transPackage;
        } else {
           return null;
        }
    }


    
}
